package cn.edu.zut.sunday.config;

import static cn.edu.zut.sunday.constant.BaseConstant.BASE_PACKAGE_NAME;

import cn.edu.zut.sunday.utils.DateUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.text.SimpleDateFormat;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Slf4j
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = BASE_PACKAGE_NAME)
public class WebConfig implements WebMvcConfigurer {

    /**
     * 添加信息转换器
     *
     * @param converters 添加信息转换器列表
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper                              om        = new ObjectMapper();
        //全局修改json时间格式
        om.setDateFormat(new SimpleDateFormat(DateUtils.DATE_FORMAT));
        converter.setObjectMapper(om);
        converters.add(converter);
    }

    /**
     * 管理静态资源
     *
     * @param registry 静态资源管理注册对象
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置swagger2-ui静态资源
        registry.addResourceHandler("/swagger-ui/**")
          .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
          .resourceChain(false);
        // 前端页面
        registry.addResourceHandler("/**")
          .addResourceLocations("classpath:/dist/");
    }

    /**
     * 配置Swagger2的可视化静态资源
     *
     * @param registry 视图资源管理注册对象
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/swagger-ui/")
          .setViewName("forward:/swagger-ui/index.html");
    }
}
